﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Security.Cryptography;

namespace Common.Util
{
    public class StringHelper
    {
        //网站安全性１：SQL 注入２：HTML注入 ３：CSRF（跨站点请求伪造）４：文件上传（FCKEditor）
        //1：sql参数或是存储过程;对于拼接sql的需要将‘替换为'';
        //2：对于一般的插入时编码（htmlencode），对于文本编辑器则需要在服务器端再过滤一下（fck客户端可以过滤）;
        //3：ViewStateUserKey = Session.SessionID;
        //4：验证权限和文本格式.

        #region 获取数量、截取、加密


        /// <summary>
        /// 判断字符是否为空（空为真）
        /// </summary>
        /// <param name="str">输入字符串</param>
        /// <returns></returns>
        public static bool IsEmpty(string str)
        {
            if (str == string.Empty)
                return true;
            else
                return false;
        }

        /// <summary>
        /// 截取字符串 得到缩略语（不区分中英文）
        /// ex
        ///   string test="fghfgj"
        ///   GetShortcutString(test,5);
        ///   result：test is fghfg
        /// </summary>
        /// <param name="obj">输入对象</param>
        /// <param name="nLen">截取数量</param>
        /// <returns>截取后字符串</returns>
        public static string GetShortcutString(object obj, int nLen)
        {
            if (obj == null || obj is System.DBNull)
                return "";
            string str = obj.ToString();
            if (str.Length <= nLen)
            {
                return str;
            }
            else
            {
                return str.Substring(0, nLen) + "...";
            }
        }

        /// <summary>
        /// 截取字符串内容 得到缩略语（区分中英文） 并
        /// ex
        ///   string test="6688电子商务"
        ///   GetShortcutString2(test,3);
        ///   result：test is 6688电
        /// </summary>
        /// <param name="obj">输入对象</param>
        /// <param name="nLen">截取数量</param>
        /// <returns>截取后字符串</returns>
        public static string GetShortcutString2(object obj, int nLen)
        {
            return GetShortcutString2(obj, nLen, "");
        }

        /// <summary>
        /// 截取字符串内容 得到缩略语（区分中英文） 并且可以在后面加后缀
        /// ex
        ///   string test="6688电子商务"
        ///   GetShortcutString2(test,3,"...");
        ///   result：test is 6688电...
        /// </summary>
        /// <param name="obj">输入对象</param>
        /// <param name="nLen">截取数量</param>
        /// <param name="postfixStr">后缀字符串</param>
        /// <returns>截取后字符串</returns>
        public static string GetShortcutString2(object obj, int nLen, string postfixStr)
        {
            if (obj == null || obj is System.DBNull)
                return "";
            string str = obj.ToString();
            string _str;
            int totalnum = str.Length;
            int num = 0;
            int i = 0;
            if (str == "")
            {
                return "";
            }
            if (nLen > totalnum)
            {
                return str;
            }

            for (i = 0; i <= (totalnum - 1); i++)
            {
                _str = str.Substring(i, 1);
                System.Byte[] _byte = System.Text.ASCIIEncoding.Unicode.GetBytes(_str);
                //判断中英文
                if (_byte[1] == 0)
                {
                    num += 1;
                }
                else
                {
                    num += 2;
                }
                if (num > nLen * 2)
                {
                    str = str.Substring(0, i) + postfixStr;
                    break;
                }

            }
            return str;
        }

        /// <summary>
        /// 消除字符串中的空格
        /// </summary>
        /// <param name="trim_string">待消除空格字符串</param>
        /// <returns>消除空格后的字符串</returns>
        public static string TrimString(string trim_string)
        {
            if (trim_string == null || trim_string == "")
                return "";
            System.Text.StringBuilder strRet = new System.Text.StringBuilder(trim_string);
            strRet.Replace(" ", "");
            //清除全角空格
            strRet.Replace("　", "");
            return strRet.ToString();

        }

        /// <summary>
        /// 找出字符在某一个数组里的索引
        /// </summary>
        /// <param name="chars"></param>
        /// <param name="c"></param>
        /// <returns></returns>
        public static int IndexOf(char[] chars, char c)
        {
            int i = 0;
            for (; i < chars.Length; i++)
            {
                if (chars[i] == c)
                    return i;
            }
            return -1;
        }

        /// <summary>
        /// 得到从第一个汉字开始的指定字符串长度
        /// </summary>
        /// <param name="source"></param>
        /// <param name="len"></param>
        /// <returns></returns>
        public static string GetSubString3(string source, int len)
        {
            System.Globalization.TextElementEnumerator te = System.Globalization.StringInfo.GetTextElementEnumerator(source);
            while (te.MoveNext())
            {
                string oneChar = te.GetTextElement();
                if (StringHelper.IsChineseChar(oneChar))
                {
                    string left = source.Substring(source.IndexOf(oneChar));

                    if (left.Length < len)
                    {
                        return left;
                    }
                    else
                    {
                        return left.Substring(0, len) + "...";
                    }
                }
            }

            return null;
        }

        /// <summary>
        /// 判断是否为汉字
        /// </summary>
        /// <param name="oneChar"></param>
        /// <returns></returns>
        private static bool IsChineseChar(string oneChar)
        {
            char[] charArray = oneChar.ToCharArray();

            int oneCharUniCode = Convert.ToInt32(charArray[0]);

            if (oneCharUniCode >= 0x4E00 && oneCharUniCode <= 0x9FAF)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="Sign">输入字符串</param>
        /// <returns></returns>
        public static string SetMd5(string Sign)
        {
            return Md5(Sign);
        }

        /// <summary>
        /// MD5 加密算法
        /// </summary>
        /// <param name="str">未加密前的字符串</param>
        /// <returns>加密后的字符串</returns>
        public static string Md5(string str)
        {
            System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
            byte[] bytes = new byte[16];
            bytes = Encoding.Default.GetBytes(str);
            //System.Text.ASCIIEncoding asc = new System.Text.ASCIIEncoding();
            //bytes = md5.ComputeHash(asc.GetBytes(str));
            return BitConverter.ToString(md5.ComputeHash(bytes)).Replace("-", "").ToLower();
        }


        #endregion

        #region 字符格式转换


        /// <summary>
        /// 对字符串文本中的特殊字符进行替换成Html，以达到文本层次清楚的目的。
        /// </summary>
        /// <param name="trans_string">将要替换的字符串</param>
        /// <returns>替换后的字符串</returns>
        public static string FormatStringHtml(string trans_string)
        {
            System.Text.StringBuilder strRet = new System.Text.StringBuilder(trans_string);
            strRet.Replace("&", "&amp;");
            strRet.Replace("<", "&lt;");
            strRet.Replace("<", "&gt;");
            strRet.Replace(" ", "&nbsp;&nbsp;");
            strRet.Replace("\n", "<br>");
            return strRet.ToString();

        }

        /// <summary>
        /// 字符串中html还原为普通文档符号
        /// ex:
        ///   string s="<br>&amp;";
        ///   string b=HtmlFormatText(s);
        ///   b的值为  \n&
        /// </summary>
        /// <param name="trans_string">待还原字符串</param>
        /// <returns>还原后的字符串</returns>
        public static string HtmlFormatText(string trans_string)
        {
            System.Text.StringBuilder strRet = new System.Text.StringBuilder(trans_string);
            strRet.Replace("&amp;", "&");
            strRet.Replace("&lt;", "<");
            strRet.Replace("&gt;", "<");
            strRet.Replace("&nbsp;&nbsp;", " ");
            strRet.Replace("&nbsp;", "");
            strRet.Replace("<br>", "\n");
            return strRet.ToString();

        }

        /// <summary>
        /// 对字符串文本中的特殊字符进行替换成Html，以达到文本层次清楚的目的。
        /// </summary>
        /// <param name="trans_string">将要替换的字符串</param>
        /// <returns>替换后的字符串</returns>
        public static string FormatString(string trans_string)
        {
            System.Text.StringBuilder strRet = new System.Text.StringBuilder(trans_string);
            strRet.Replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
            strRet.Replace("\n", "<br>");
            return strRet.ToString();

        }

        /// <summary>
        /// 字符串中html还原为普通文档符号
        /// ex:
        ///   string s="<br>&amp;";
        ///   string b=HtmlFormatText(s);
        ///   b的值为  \n&
        /// </summary>
        /// <param name="trans_string">待还原字符串</param>
        /// <returns>还原后的字符串</returns>
        public static string HtmlFormat(string trans_string)
        {
            System.Text.StringBuilder strRet = new System.Text.StringBuilder(trans_string);
            strRet.Replace("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;", "\t");
            strRet.Replace("<br>", "\n");
            return strRet.ToString();

        }

        /// <summary>
        /// 还原字符串中的特殊字符
        /// </summary>
        /// <param name="trans_string">待还原字符串</param>
        /// <returns>还原后的字符串</returns>
        public static string HtmlFormatText2(string trans_string)
        {
            System.Text.StringBuilder strRet = new System.Text.StringBuilder(trans_string);

            strRet.Replace("&amp;", "&");
            strRet.Replace("&lt;", "<");
            strRet.Replace("&gt;", "<");
            strRet.Replace("&nbsp;", "");
            strRet.Replace("<br>", "\n");

            return strRet.ToString();

        }

        /// <summary>
        /// 转化为xml可以处理的格式
        /// </summary>
        /// <param name="s">要转换的字符串</param>
        /// <returns></returns>
        public static string FormatXml(string s)
        {
            s = s.Replace("<", "&lt;");
            s = s.Replace(">", "&gt;");
            s = s.Replace("'", "&apos");
            s = s.Replace("\"", "&quot;");
            s = s.Replace("&", "&amp;");
            return s;
        }

        /// <summary>
        /// 将xml的特殊格式还原
        /// </summary>
        /// <param name="s">要转换的字符串</param>
        /// <returns></returns>
        public static string XmlFormatText(string s)
        {
            s = s.Replace("&lt;", "<");
            s = s.Replace("&gt;", ">");
            s = s.Replace("&apos", "'");
            s = s.Replace("&quot;", "\"");
            s = s.Replace("&amp;", "&");
            return s;
        }

        /// <summary>
        /// 过滤特殊字符串
        /// </summary>
        /// <param name="src"></param>
        /// <returns></returns>
        public static string encoding(string src)
        {
            System.Text.StringBuilder strRet = new System.Text.StringBuilder(src);
            if (src == null)
            { return ""; }
            if (src != null)
            {
                src = src.Trim();
                strRet.Replace("\"", " ");
                strRet.Replace("<", "&lt;");
                strRet.Replace(">", "&gt;");
                strRet.Replace("\'", "&apos;");
                strRet.Replace("%", "&pc;");
                strRet.Replace("_", "&ul;");
                strRet.Replace("#", "&shap;");
                strRet.Replace("?", "&ques;");
            }
            return strRet.ToString();

        }

        /// <summary>
        /// 功能：此方法用来格式化从量表中返回的量表介绍信息，转换成对应的html格式
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string EncodeScaleIntroduceFromDLL(string str)
        {
            if (string.IsNullOrEmpty(str))
                return null;
            StringBuilder builder = new StringBuilder(str);
            if (builder == null)
                return null;
            builder.Replace(" ", "&nbsp;");
            builder.Replace("\n", "<br>");
            return builder.ToString();
        }

        public static string DecodeScaleIntroduceFromDll(string str)
        {
            if (string.IsNullOrEmpty(str))
                return null;
            StringBuilder builder = new StringBuilder(str);
            if (builder == null)
                return null;
            builder.Replace("&nbsp;", " ");
            builder.Replace("<br>", "\n");
            return builder.ToString();
        }

        /// <summary>
        /// 反过滤特殊字符串
        /// </summary>
        /// <param name="src"></param>
        /// <returns></returns>

        public static string decoding(string src)
        {

            if (src == null)

                return "";

            string result = src;

            result = result.Replace("“", "\"").Replace("&apos;", "\'");

            result = result.Replace("<", "<").Replace(">", ">");

            result = result.Replace("&", "&");

            result = result.Replace("&pc;", "%").Replace("&ul", "_");

            result = result.Replace("&shap;", "#").Replace("&ques", "?");

            return result;

        }

        public static bool IsNumber(string value)
        {
            Regex reg = new Regex("^[0-9]+$");
            Match ma = reg.Match(value);

            return ma.Success;
        }

        #endregion

        #region 字符逻辑转换


        /// <summary>
        /// 将字符串根据分割符转换为二维数组
        /// 
        /// string s = "a=1,b=2,c=3;a=5,b=6,c=7;a=0,b=23,c=90" ;
        /// string[,] a = GetArrayFromString2(s,';',',') ;
        /// //a now is
        /// 1		2		3
        /// 5		6		7
        /// 0		23		90
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="c1">第一分割符</param>
        /// <param name="c2">第二分割符</param>
        /// <returns>数组</returns>
        public static string[,] GetArrayFromString2(string str, char c1, char c2)
        {
            if (str == null || str == "")
                return null;
            string[] a1 = str.Split(new char[] { c1 });
            string[] a2 = a1[0].Split(new Char[] { c2 });

            string[,] a3 = new string[a1.Length, a2.Length];
            for (int i = 0; i < a1.Length; i++)
            {
                a2 = a1[i].Split(new char[] { c2 });
                for (int j = 0; j < a2.Length; j++)
                {
                    a3[i, j] = GetSuffixString(a2[j], '=');
                }
            }
            return a3;
        }

        /// <summary>
        /// 将字符串根据分割符转换为二维数组
        /// string s = "a=1,b=2,c=3;a=5,b=6,c=7;a=0,b=23,c=90" ;
        /// string[,] a = GetArrayFromString2(s,';',',') ;
        /// //a now is
        /// a=1		b=2		c=3
        /// a=5		b=6		c=7
        /// a=0		b=23	c=90
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="c1">第一分割符</param>
        /// <param name="c2">第二分割符</param>
        /// <returns>数组</returns>
        public static string[,] GetArrayFromString3(string str, char c1, char c2)
        {
            //
            if (str == null || str == "")
                return null;
            string[] a1 = str.Split(new char[] { c1 });
            string[] a2 = a1[0].Split(new Char[] { c2 });

            string[,] a3 = new string[a1.Length, a2.Length];
            for (int i = 0; i < a1.Length; i++)
            {
                a2 = a1[i].Split(new char[] { c2 });
                for (int j = 0; j < a2.Length; j++)
                {
                    a3[i, j] = a2[j];
                }
            }
            return a3;
        }

        /// <summary>
        /// 从一个格式如 001,002,003 字符串里得到一个数组
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>数组，如果没有内容，将反回null</returns>
        public static string[] GetArrayFromString(string strSource, char ch)
        {
            return strSource.Split(new char[] { ch });
        }

        /// <summary>
        /// 从一个数组里得到字符串
        /// string s = GetStringFromArray(new string[]{"sss","qqq","www","ttt"},"'",',');
        /// s now is "'sss','qqq','www','ttt'"
        /// </summary>
        /// <param name="ar">字符串数组</param>
        /// <param name="m">修饰字符串</param>
        /// <param name="sp">分隔符号</param>
        /// <returns>字符串</returns>
        public static string GetStringFromArray(string[] ar, string m, char sp)
        {
            if (ar == null || ar.Length == 0)
                return string.Empty;
            string ms = m == null ? string.Empty : m;
            System.Text.StringBuilder strret = new System.Text.StringBuilder(string.Empty);
            for (int i = 0; i < ar.Length; i++)
            {
                strret.Append(ms);
                strret.Append(ar[i]);
                strret.Append(ms);
                if (i < (ar.Length - 1))
                {
                    strret.Append(sp);
                }
            }
            return strret.ToString();
        }

        /// <summary>
        /// 从一个数组里得到字符串
        /// </summary>
        /// <param name="ar">对象数组</param>
        /// <param name="m">修饰字符串</param>
        /// <param name="sp">分隔符号</param>
        /// <returns>字符串</returns>
        public static string GetStringFromArray(object[] ar, string m, char sp)
        {
            if (ar == null || ar.Length == 0)
                return string.Empty;
            string ms = m == null ? string.Empty : m;
            System.Text.StringBuilder strret = new System.Text.StringBuilder(string.Empty);
            for (int i = 0; i < ar.Length; i++)
            {
                strret.Append(ms);
                strret.Append(ar[i] == null ? "" : ar[i].ToString());
                strret.Append(ms);
                if (i < (ar.Length - 1))
                {
                    strret.Append(sp);
                }
            }
            return strret.ToString();
        }

        /// <summary>
        /// 从一个数组里得到字符串
        /// string s = GetStringFromArray(new string[]{"sss","qqq","www","ttt"} , " and " );
        /// s now is "'sss and qqq and www and ttt"
        /// </summary>
        /// <param name="ar">字符串数组</param>
        /// <param name="sp">分隔符号</param>
        /// <returns>字符串</returns>
        public static string GetStringFromArray(string[] ar, string sp)
        {
            if (ar == null || ar.Length == 0)
                return string.Empty;
            System.Text.StringBuilder strret = new System.Text.StringBuilder(string.Empty);
            for (int i = 0; i < ar.Length; i++)
            {
                strret.Append(ar[i]);
                if (i < (ar.Length - 1))
                {
                    strret.Append(sp);
                }
            }
            return strret.ToString();

        }

        /// <summary>
        /// 从一个格式如 acode=001#b=1#c=001,002,003 的字符串里得到一个哈西表。
        /// System.Collections.Hashtable ht = GetCodeNameArrayFromString("acode=001#b=1#c=01,02,03");
        /// string s1 = (string)ht["acode"] ;//now 001
        /// string s2 = (string)ht["b"] ;//now 1
        /// string s3 = (string)ht["b"] ;//now 01,02,03
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>哈西表</returns>
        public static System.Collections.Hashtable GetCodeNameArrayFromString(string str)
        {
            System.Collections.Hashtable ht = new System.Collections.Hashtable();
            int length = str.Length;
            int index = -1;
            do
            {
                int oldindex = index + 1;
                index = str.IndexOf('#', oldindex);
                string stemp = string.Empty;
                if (index == -1)
                    stemp = str.Substring(oldindex, length - oldindex);
                else
                    stemp = str.Substring(oldindex, index - oldindex);
                if (stemp != string.Empty)
                {
                    string name = string.Empty;
                    string code = GetCodeNameFromString(stemp, '=', out name);
                    ht.Add(code, name);
                }
            } while (index != -1);
            return ht;
        }

        /// <summary>
        /// 从一个形如 acode:B001 或者 B001=张三 的字符串里得到其两端的数据
        /// 例如：
        ///		string strName = "";
        ///		string strCode = GetCodeNameFromString("code=001",'=',out strName);
        ///		//now strCode is 'code'
        ///		//now strName is '001'
        /// </summary>
        /// <param name="str">源字符串</param>
        /// <param name="sp">分隔符号</param>
        /// <param name="name">返回的名</param>
        /// <returns>码</returns>
        public static string GetCodeNameFromString(string str, char sp, out string name)
        {
            //name = string.Empty ;
            int i = str.IndexOf(sp, 0);
            string code = i == -1 ? str : str.Substring(0, i);
            name = i == -1 ? str : str.Substring(i + 1, str.Length - i - 1);
            return code;
        }

        /// <summary>
        /// 从一个形式如 xxx:xxxxx 的字符串里得到前缀子字符串
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="ch">分隔字符</param>
        /// <returns>前缀子字符串</returns>
        public static string GetPrefixString(string str, char ch)
        {
            int i = str.IndexOf(ch, 0);
            return i == -1 ? str : str.Substring(0, i);
        }

        /// <summary>
        /// 从一个形式如 xxx:xxxxx 的字符串里得到后缀子字符串
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="ch">分隔字符</param>
        /// <returns>后缀子字符串</returns>
        public static string GetSuffixString(string str, char ch)
        {
            int i = str.IndexOf(ch, 0);
            return i == -1 ? str : str.Substring(i + 1, str.Length - i - 1);
        }

        /// <summary>
        /// 从一个形式如 xxx:xxx:xxxxx 的字符串里得到最后一个分隔字符后的子字符串
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="ch">分隔字符</param>
        /// <returns>后缀子字符串</returns>
        public static string GetSuffixString2(string str, char ch)
        {
            int i = str.LastIndexOf(ch, str.Length - 1);
            return i == -1 ? str : str.Substring(i + 1, str.Length - i - 1);
        }

        /// <summary>
        /// 根据一个格式字符串返回其中的编码
        /// 例如:
        /// string s = "001=办公室#002=财务部" ;
        /// string[] a = GetCodeArray(s,'#','=') ;
        /// //a now include "001","002"
        /// </summary>
        /// <param name="strSource"></param>
        /// <param name="sp1"></param>
        /// <param name="sp2"></param>
        /// <returns></returns>
        public static string[] GetCodeArray(string strSource, char sp1, char sp2)
        {
            string[] a = GetArrayFromString(strSource, sp1);
            string[] retA = new string[a.Length];
            for (int i = 0; i < a.Length; i++)
            {
                retA[i] = GetPrefixString(a[i], sp2);
            }
            return retA;
        }

        /// <summary>
        /// 根据一个格式字符串返回其中的编码
        /// 例如:
        /// string s = "001=办公室#002=财务部" ;
        /// string[] a = GetNameArray(s,'#','=') ;
        /// //a now include "办公室","财务部"
        /// </summary>
        /// <param name="strSource"></param>
        /// <param name="sp1"></param>
        /// <param name="sp2"></param>
        /// <returns></returns>
        public static string[] GetNameArray(string strSource, char sp1, char sp2)
        {
            string[] a = GetArrayFromString(strSource, sp1);
            string[] retA = new string[a.Length];
            for (int i = 0; i < a.Length; i++)
            {
                retA[i] = GetPrefixString(a[i], sp2);
            }
            return retA;
        }

        /// <summary>
        /// 根据一个格式字符串返回其中的编码
        /// 例如:
        /// string s = "001=办公室#002=财务部" ;
        /// string[,] codenames = GetCodeNameArray(s,'#','=') ;
        /// //codenames now include
        ///		"001","办公室"
        ///		"002","财务部"
        /// </summary>
        /// <param name="strSource">格式字符串</param>
        /// <param name="sp1">分隔符号1</param>
        /// <param name="sp2">分隔符号2</param>
        /// <returns>包括码名映射的二维数组</returns>
        public static string[,] GetCodeNameArray(string strSource, char sp1, char sp2)
        {
            string[] a = GetArrayFromString(strSource, sp1);
            string[,] retA = new string[a.Length, 2];
            for (int i = 0; i < a.Length; i++)
            {
                retA[i, 0] = GetPrefixString(a[i], sp2);
                retA[i, 1] = GetSuffixString(a[i], sp2);
            }
            return retA;
        }


        #endregion

        #region        过滤html标签

        // 删除指定标记的html代码
        public static string RemoveHtmlByTag(string content, string[] tags)
        {
            if (content == "" || tags.Length == 0)
            {
                return "";
            }
            string regexstr1, regexstr2;
            foreach (string tag in tags)
            {
                if (tag != "")
                {
                    regexstr1 = string.Format(@"<{0}([^>])*>", tag);
                    regexstr2 = string.Format(@"</{0}([^>])*>", tag);
                    content = Regex.Replace(content, regexstr1, string.Empty, RegexOptions.IgnoreCase);
                    content = Regex.Replace(content, regexstr2, string.Empty, RegexOptions.IgnoreCase);
                }
            }
            return content;

        }

        // 清除字符串中所有的html代码
        public static string RemoveHtml(string content)
        {
            if (content == "")
            {
                return "";

            }
            string newstr = StringHelper.ReplaceBadChar(content);
            string regexstr = @"<[^>]*>";

            content = Regex.Replace(newstr, regexstr, string.Empty, RegexOptions.IgnoreCase);
            content = content.Replace("&nbsp;&nbsp;", " ");
            content = content.Replace("&nbsp;", "");
            return content;
        }

        //过滤攻击性字符
        public static string StripHTML(string strHtml)
        {
            string[] aryReg ={
								  @"<script[^>]*?>.*?</script>",

								  @"<(\/\s*)?!?((\w+:)?\w+)(\w+(\s*=?\s*(([""'])(\\[""'tbnr]|[^\7])*?\7|\w+)|.{0})|\s)*?(\/\s*)?>",
								  @"([\r\n])[\s]+",
								  @"&(quot|#34);",
								  @"&(amp|#38);",
								  @"&(lt|#60);",
								  @"&(gt|#62);", 
								  @"&(nbsp|#160);", 
								  @"&(iexcl|#161);",
								  @"&(cent|#162);",
								  @"&(pound|#163);",
								  @"&(copy|#169);",
								  @"&#(\d+);",
								  @"-->",
								  @"<!--.*\n"
         
							  };

            string[] aryRep = {
								   "",
								   "",
								   "",
								   "\"",
								   "&",
								   "<",
								   ">",
								   " ",
								   "\xa1",//chr(161),
								   "\xa2",//chr(162),
								   "\xa3",//chr(163),
								   "\xa9",//chr(169),
								   "",
								   "\r\n",
								   ""
							   };

            string newReg = aryReg[0];
            string strOutput = strHtml;
            for (int i = 0; i < aryReg.Length; i++)
            {
                Regex regex = new Regex(aryReg[i], RegexOptions.IgnoreCase);
                strOutput = regex.Replace(strOutput, aryRep[i]);
            }

            strOutput.Replace("<", "");
            strOutput.Replace(">", "");
            strOutput.Replace("\r\n", "");


            return strOutput;
        }

        public static string FckEditEncode(string editHtmlOrNot)
        {
            if (string.IsNullOrEmpty(editHtmlOrNot))
                return null;

            string result = editHtmlOrNot;
            result = Regex.Replace(result, @"<\s*iframe[\s\S]*?>", "&lt;iframe&gt;");// iframe
            result = Regex.Replace(result, @"<\s*frameset[\s\S]*?>", "&lt;frameset&gt;");// frameset
            result = Regex.Replace(result, @"<\s*frame[\s\S]*?>", "&lt;frame&gt;");// frame
            result = Regex.Replace(result, @"<\s*script[\s\S]", "&lt;script&gt;");
            result = Regex.Replace(result, @"<\/script\s*>", "&lt;/script&gt;");
            result = Regex.Replace(result, @"<%[\s\S]*?%>", "");
            result = Regex.Replace(result, @"<\?[\s\S]*?\?>", "");
            result = Regex.Replace(result, @"(<asp:[^\>]+>[\s|\S]*?<\/asp:[^\>]+>)|(<asp:[^\>]+\/>)", "");

            return result;
        }

        public static string RemoveUnsafeHtml(string content)
        {
            content = Regex.Replace(content, @"(\<|\s+)o([a-z]+\s?=)", "$1$2", RegexOptions.IgnoreCase);
            content = Regex.Replace(content, @"(script|frame|form|meta|behavior|style)([\s|:|>])+", "$1.$2", RegexOptions.IgnoreCase);
            return content;
        }
        public static string ReplaceBadChar(string str)
        {
            if (!string.IsNullOrEmpty(str))
            {
                str = Regex.Replace(str, @"(?s)/\*.*?\*/", "", RegexOptions.IgnoreCase); //删除注释:/* */
                str = Regex.Replace(str, @"(?s)<script.*?>.*?</script>", "", RegexOptions.IgnoreCase); //删除脚本
                str = Regex.Replace(str, @"(?s)<iframe.*?>.*?</iframe>", "", RegexOptions.IgnoreCase); //过滤Ifrmae
                str = Regex.Replace(str, @"(?s)<style.*?>.*?</style>", "", RegexOptions.IgnoreCase);
                //需要把用户自己添加的样式都删除
                //<link href="/scripts/PopBox/stylesheets/Styles.css" rel="stylesheet" type="text/css" />
                str = Regex.Replace(str, @"(?s)<link[^>]+href+([^>]+?)>", "", RegexOptions.IgnoreCase);

                //替换一些比较特殊的字符 
                // str = str.Replace("&nbsp;", " "); //将&nbsp;替换为一个空格
                str = str.Replace("&mdash;", "－");//将&mdash;替换为-
                str = str.Replace("&rdquo;", "”");
                str = str.Replace("&ldquo;", "“");
                str = str.Replace("&le;", "<=");
                str = str.Replace("&ne;", "!=");
                str = str.Replace("&ge;", ">=");

                //<img src="" onerror="" /> <([^>|^<]+?on)([\w]+[^=]+?)=([^>]+?)>
                str = Regex.Replace(str, @"<([^>|^<]+?on)([a-z|A-Z]+[^=]+?)=([^>]+?)>",
                "<$1_$2=$3>", RegexOptions.IgnoreCase);//过滤可能的XSS攻击,脚本事件                


                //style="XSS:expression(alert(/xss/))"
                str = str.Replace("expression", "Ｅxpression");//过滤所有可能的脚本
                str = Regex.Replace(str, @"(style(.*))=(.*)(expression)", "$1=$3", RegexOptions.IgnoreCase); //过滤样式中，可能带有的脚本事件   
                //<iframe src=

                str = Regex.Replace(str, "(?s)<iframe.*?>.*?</iframe>", "", RegexOptions.IgnoreCase);//过滤Ifrmae;                  


                //javascript:
                str = str.Replace("javascript:", "ｊａｖａｓｃｒｉｐｔ：");//过滤<img src="javascript:alert(/xss/)" />

                str = str.Replace("vbscrript:", "ｖｂｓｃｒｉｐｔ：");//过滤ｖｂｓｃｒｉｐｔ

                str = str.Replace("script", "ｓｃｒｉｐｔ");//过滤所有可能的脚本

                str = str.Replace("iframe", "ｉｆｒａｍｅ");//过滤所有可能的脚本

                //防止转码XSS攻击:<img src="&#106&#97&#118&#97&#115&#99&#114&#105&#112&#116&#58&#97&#108&#101&#114&#116&#40&#39&#88&#83&#83&#39&#41&#59">

                str = str.Replace("#", "＃");//过滤#
                // str = str.Replace("&", "＆");//过滤&
                str = str.Replace("%", "％");//过滤%

                // 替换为全角
                str = str.Replace("'", "＇");
                str = str.Replace("--", "－－");
                str = str.Replace(";", "；");
                str = str.Replace("+", "＋");
                //   str = str.Replace("/", "／");  图片路径里有 暂不替换
                //str = str.Replace("&", "＆");
                str = str.Replace(",", "，");
                str = str.Replace("%", "％");
                str = str.Replace("-", "－");
                str = str.Replace("(|)", "（｜）");
                str = str.Replace("[|]", "【｜】");
                str = str.Replace("{", "｛");
                str = str.Replace("}", "｝");
                str = str.Replace("*", "＊");
                str = str.Replace("!", "！");
                //str = str.Replace("<", "&lt;");
                //str = str.Replace(">", "&gt;");


                //<img STYLE="background-image: \75\72\6c\28\6a\61\76\61\73\63\72\69\70\74\3a\61\6c\65\72\74\28\27\58\53\53\27\29\29"> 

                str = str.Replace("\\", "/");//过滤\ 防止连接１６进制的攻击

                if (str.IndexOf("<script") >= 0)
                    str = str.Replace("<", "&lt;--script");

                if (str.IndexOf("'") > 0)
                    str = str.Replace("'", "’");

            }
            return str;
        }


        #endregion

        #region sql注入

        /// <summary>
        /// 检测是否含有危险字符  如果返回为false 则代表包含特殊危险字符  返回为true 则代表安全
        /// </summary>
        /// <param name="content"></param>
        /// <returns>bool</returns>
        public static bool IsSafe(string content)
        {
            return !Regex.IsMatch(content, @"[-|;|,|\/|\(|\)|\[|\]|\}|\{|%|~|#|%|^|&|(|)|@|\*|!|\']");
        }

        //过滤sql关键字
        public static string RemoveUnsafeSql(string Htmlstring)
        {
            string p = @"[-|;|,|\/|\(|\)|\[|\]|\}|\{|%|~|#|%|^|&|(|)|@|\*|!|\']";
            return Regex.Replace(Htmlstring, p, "");
        }

        //过滤危险字符
        public static string Filter(string content)
        {
            // 过滤攻击性字符
            content = ReplaceBadChar(content);
            //过滤sql关键字
            content = RemoveUnsafeSql(content);
            return content;
        }


        #endregion

        #region fck内容显示简短文字

        public static string fckshow(string souse)
        {
            if (souse == "")
            {
                return "";
            }
            souse = StringHelper.RemoveHtml(souse);
            souse = StringHelper.ReplaceBadChar(souse);
            souse = StringHelper.GetShortcutString(souse, 100);
            return souse;
        }

        #endregion

    }
}
